import Vue from 'vue'
import Router from 'vue-router'
import Login from "../components/login";
import Home from "../components/Home";
import Home01 from "../components/Home01";

import Welcome from "../components/Welcome"

/*设置路由守卫后，this.$router.push(会报错Uncaught (in promise)*/
const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
};


Vue.use(Router)

const router = new Router({
  routes: [
    { path: '/', redirect: '/login' },
    { path: '/login', component: Login },
    {
      path: '/home01', component: Home01,

    },
    {
      path: '/home', component: Home,
      redirect:'/welcome',
      children: [{
        path: '/welcome',
        component: Welcome
      }]
    },
  ]
})


// 挂载路由导航守卫
// 一to将要访问的页面路径  二from 从哪个路径跳转而来的 三next放行的函数 next('/')强制跳转
    router.beforeEach((to, from, next) =>{
      if(to.path ==='/login') return next();

      const tokenStr = window.sessionStorage.getItem('token');
            console.log(tokenStr)
      if(!tokenStr) return next('/login');
      next()
    })
  //   router.beforeEach((to,form,next) =>{
  //     //如果进入到的路由是登录页或者注册页面，则正常展示
  //     if(to.path == '/login'  ){     
  //         next();
  //     }else if( !(sessionStorage.getItem('token')) ){
  //         alert("还没有登录，请先登录！");
  //         next('/login');     //转入login登录页面，登录成功后会将token存入localStorage
  //     }else{
  //         next();
  //     }
  // })
  

    // const originalPush = Router.prototype.push
    // Router.prototype.push = function push(location) {
    //   return originalPush.call(this, location).catch(err => err)
    // }

export default router